package com.atilim.cargo.web;

import java.util.LinkedList;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import com.atilim.cargo.business.AuthorizationBean;
import com.atilim.cargo.business.MapBean;
import com.atilim.cargo.model.Agency;
import com.atilim.cargo.model.Road;
import com.atilim.cargo.model.User;
import com.atilim.cargo.model.Vertex;
import com.atilim.cargo.test.OpenStreetMap;
import com.atilim.cargo.test.TestData;

import com.atilim.cargo.util.Utility;

/**
 * Servlet implementation class PublicServlet
 */
@WebServlet("/PublicServlet")
public class PublicServlet extends BaseServlet {
	
	

	@Inject
	AuthorizationBean authenticationBean;
	
	@Inject
	MapBean mapBean;

	@Override
	public void execute(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		
		String cmd = req.getParameter("cmd");
		if ("login".equals(cmd)) {
			login(req, resp);
		
		} else if ("listRoad".equals(cmd)) {
			loadRoad(req, resp);
		} else if ("listVertex".equals(cmd)) {
			listVertex(req, resp);
		} else if ("drawShortestPath".equals(cmd)) {
			drawShortestPath(req, resp);
		} else if ("listAgency".equals(cmd)) {
			listAgency(req, resp);
		}
		
	}
	
	private void drawShortestPath (HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String nodeDestination = req.getParameter("n1");
		String nodeTarget = req.getParameter("n2");
		
		//Yeni istekte bütün node'ların min distance değerlerine tekrar sonsuz'a set ediyoruz 
		for (Vertex v : OpenStreetMap.vertexes) {
			v.minDistance = Double.POSITIVE_INFINITY;
		}
		
		Vertex dest = mapBean.locateNearestPoint(nodeDestination);
		Vertex target = mapBean.locateNearestPoint(nodeTarget);
		
		List<Vertex> path = mapBean.drawToShortestPath(dest, target);
		
		if (path == null || path.size() == 0) {
			throw new Exception("Yol bulunamadı");
		}
		
		for (Vertex vertex : path) {
			System.out.println(vertex);
		}
		
		JSONArray arr = new JSONArray();
		int i = 0;
		double distance = Utility.distanceOfPath(path);
		for (Vertex v : path) {
			JSONObject o = new JSONObject();
			
			o.put("id", i++);
			o.put("name", v.getName());
			o.put("totalDistance", distance);

			o.put("lat", Double.parseDouble(v.getLat()));
			o.put("lon", Double.parseDouble(v.getLon()));
			arr.put(o);
		}
		OpenStreetMap.vertexes.remove(dest);
		OpenStreetMap.vertexes.remove(target);
		
		resp.getWriter().write(arr.toString());
		
	}
	
	
	
	private void listVertex (HttpServletRequest req, HttpServletResponse resp) throws Exception {
		//TestData.refresh();
		JSONObject obj = new JSONObject();
		JSONArray arr = new JSONArray();
		
		int i = 0;
		for (Vertex v : OpenStreetMap.vertexes) {
			
			
			
			JSONObject o = new JSONObject();
			o.put("id", i++);
			o.put("name", v.getName());
			o.put("lat", Double.parseDouble(v.getLat()));
			o.put("lon", Double.parseDouble(v.getLon()));
			arr.put(o);
		}
		
		obj.put("items", arr);
		obj.put("success", true);
		
		resp.getWriter().write(obj.toString());
	}

	private void listAgency (HttpServletRequest req, HttpServletResponse resp) throws Exception {
		//TestData.refresh();
		JSONObject obj = new JSONObject();
		JSONArray arr = new JSONArray();
		
		int i = 0;
		for (Agency agency : TestData.agencySet) {
			
			
			
			JSONObject o = new JSONObject();
			o.put("id", i++);
			o.put("name", agency.getName());
			o.put("lat", agency.getLat());
			o.put("lon", agency.getLon());
			arr.put(o);
		}
		
		obj.put("items", arr);
		obj.put("success", true);
		
		resp.getWriter().write(obj.toString());
	}
	
	private void loadRoad (HttpServletRequest req, HttpServletResponse resp) throws Exception {
		
		
		JSONObject obj = new JSONObject();
		JSONArray arr = new JSONArray();
		
		int i = 0;
		for (Road r : OpenStreetMap.roads) {
			
			
			
			JSONObject o = new JSONObject();
			o.put("id", i++);
			o.put("lat1", Double.parseDouble(r.getV1().getLat()));
			o.put("lon1", Double.parseDouble(r.getV1().getLon()));
			o.put("lat2", Double.parseDouble(r.getV2().getLat()));
			o.put("lon2", Double.parseDouble(r.getV2().getLon()));
			arr.put(o);
		}
		
		obj.put("items", arr);
		obj.put("success", true);
		
		resp.getWriter().write(obj.toString());
		
	}
	
	
	
	private void login (HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		User user = authenticationBean.getUser(username, password);
		if (user != null) {
			resp.sendRedirect("index.jsp");			
		} else {
			req.getSession().setAttribute("HATA", "Hatalı Kullanıcı girişi");
			resp.sendRedirect("giris.jsp");			
		}		
	}

}
